<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.status" style="display: none;"/>
        <el-input v-model="query.createBy" style="display: none;"/>
        <!-- <el-select v-model="query.purchaseAttribute" size="small" placeholder="采购性质" class="filter-item" style="width: 200px" @change="crud.toQuery">
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select> -->
        <date-range-picker v-model="query.createTime" class="date-item" />
        <rrOperation />
      </div>      
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          v-permission="['admin','prePurchaseRequestDetail:add']"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-upload"
          @click="toUpload()"
        >上传
        </el-button>
        <el-button
          slot="right"
          v-permission="['admin','prePurchaseRequestDetail:audit']"
          class="filter-item"
          size="mini"
          type="info"
          icon="el-icon-upload"
          :disabled="crud.selections.length === 0"
          @click="doAudit(crud.selections)"
        >推送
        </el-button>
      </crudOperation>
      <!--上传表单组件-->
      <el-dialog :visible.sync="uploadDialog" title="文件上传" width="500px">
        <el-form ref="uploadForm" size="small" label-width="80px">
        <!--   <el-form-item label="文件名">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item> -->
          <!-- <el-form-item label="供应商">
            <el-input v-model="form.name" style="width: 370px;" />l
          </el-form-item> -->
          <!-- <el-form-item label="供应商" prop="supplierName">
            <el-select v-model="form.supplierName" clearable size="small" class="filter-item" style="width: 370px" >
              <el-option v-for="item in suppliers" :key="item.supplierName" :label="item.supplierName" :value="item.supplierName" />
            </el-select>
          </el-form-item>
          <el-form-item label="采购性质" prop="purchaseAttribute">
            <el-select v-model="form.purchaseAttribute" clearable size="small" class="filter-item" style="width: 370px" >
              <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
            </el-select>
          </el-form-item> -->
          <!--   上传文件   -->
          <el-form-item label="上传">
            <el-upload
              ref="upload"
              :limit="1"
              :before-upload="beforeUpload"
              :auto-upload="false"
              :headers="headers"
              :on-success="handleSuccess"
              :on-error="handleError"
              :action="baseApi + '/api/prePurchaseRequestDetail/upload'"
            >
              <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
              <div slot="tip" class="el-upload__tip">可上传任意格式文件，且不超过100M</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="cancelUploadDialog()">取消</el-button>
          <el-button :loading="loading" type="primary" @click="upload">确认</el-button>
        </div>
      </el-dialog>      
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
          <!-- <el-form-item label="b2b号">
            <el-input v-model="form.b2b" style="width: 370px;" />
          </el-form-item> -->
          <!-- <el-form-item label="序号">
            <el-input v-model="form.index" style="width: 370px;" />
          </el-form-item> -->
          <el-form-item label="型号">
            <el-input v-model="form.model" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="数量">
            <el-input v-model="form.quantity" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="期望交付日">
            <el-date-picker v-model="form.expectedDeliveryDate" type="date" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="客户">
            <el-input v-model="form.customer" style="width: 370px;" />
          </el-form-item>
          <!-- <el-form-item label="入库数">
            <el-input v-model="form.godownQuantity" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="在途数">
            <el-input v-model="form.onPassageQuantity" style="width: 370px;" />
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="auditDialog" title="请购单推送" append-to-body top="30px" width="500px">
        <el-form ref="auditForm" :model="auditForm" :rules="auditRules" size="small" label-width="100px">
          <!-- <el-form-item label="文件名">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item> -->
          <!-- <el-form-item label="供应商">
            <el-input v-model="form.name" style="width: 370px;" />l
          </el-form-item> -->
          <!-- <el-form-item label="ID" v-if="false==true" type="hidden" prop="id">
            <el-input  v-model="auditForm.id"></el-input>
          </el-form-item> -->
          <!-- <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="auditForm.supplierName"></el-input>
          </el-form-item>           
          <el-form-item label="采购性质" prop="purchaseAttribute">
            <el-input v-model="auditForm.purchaseAttribute"></el-input>
          </el-form-item>           -->
          <el-form-item label="供应商" prop="supplierName">
            <el-select v-model="auditForm.supplierName" clearable size="small" class="filter-item" style="width: 370px" >
              <el-option v-for="item in suppliers" :key="item.supplierName" :label="item.supplierName" :value="item.supplierName" />
            </el-select>
          </el-form-item>
          <el-form-item label="采购性质" prop="purchaseAttribute">
            <el-select v-model="auditForm.purchaseAttribute" clearable size="small" class="filter-item" style="width: 370px" >
              <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="cancelAuditDialog()">取消</el-button>
          <el-button type="primary" @click="passAudit(crud.selections)">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column prop="b2b" label="b2b号" /> -->
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <!-- <el-table-column prop="status" label="状态" /> -->
        <el-table-column prop="status" label="状态" :formatter="getStatusLable">
          <!-- <template slot-scope="scope">
            {{getStatusLable(scope.row.status)}}
          </template> -->
        </el-table-column>    
        <el-table-column prop="model" label="型号" />   
        <el-table-column prop="quantity" label="数量" />

        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="customer" label="客户" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="expectedDeliveryDate" label="期望交付日" :formatter="formatDate"/>
        <!-- <el-table-column prop="godownQuantity" label="入库数" />
        <el-table-column prop="onPassageQuantity" label="在途数" /> -->
        <!-- <el-table-column v-if="checkPer(['admin','prePurchaseRequestDetail:edit','prePurchaseRequestDetail:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column> -->
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import crudPrePurchaseRequestDetail from '@/api/prePurchaseRequestDetail'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import dateRangePicker from '@/components/DateRangePicker'
import supplierRequest from '@/api/supplier'
import moment from 'moment'
// import dictDetailRequest from '@/api/system/dictDetail'


const defaultForm = { id: null, purchaseRequestId: null, b2b: null, index: null, model: null, quantity: null, expectedDeliveryDate: null, remark: null, customer: null, godownQuantity: null, onPassageQuantity: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'PrePurchaseRequestDetail',
  components: { pagination, crudOperation, rrOperation, udOperation, dateRangePicker },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '请购单明细', url: 'api/prePurchaseRequestDetail', queryOnPresenterCreated: false, idField: 'id', sort: ['status,asc', 'id,desc'], crudMethod: { ...crudPrePurchaseRequestDetail }})
  },
  dicts: ['aduit_status'],
  data() {
    return {
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'prePurchaseRequestDetail:add'],
        edit: ['admin', 'prePurchaseRequestDetail:edit'],
        del: ['admin', 'prePurchaseRequestDetail:del']
      },
      rules: {
      },
      auditRules: {

      },
      auditForm: {
        supplierName: '',
        purchaseAttribute: ''
      },
      enabledTypeOptions: [
        { key: '大货', display_name: '大货' },
        { key: '直发', display_name: '直发' }
      ],
      auditDialog: false,
      uploadDialog: false,
      loading: false,
      suppliers: []
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi',
      'fileUploadApi'
    ])
  },  
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    indexMethod(index){
      return (index + 1) + (this.crud.page.page -1) * this.crud.page.size
    },
    calculateDate(days) {
      const now = new Date();
      now.setDate(now.getDate() + days);
      return now;
    },
    formatDate(row, column) {
      let data = row[column.property]
      if (data == null) {
        return null
      }
      return moment(data).format('YYYY-MM-DD')
    },
    toUpload() {
      this.uploadDialog = true
    },
    cancelUploadDialog(){
      this.uploadDialog = false
    },
    cancelAuditDialog() {
      this.auditDialog = false
    },
    passAudit(datas) {
      let ids = datas.map(item => item.id);
      crudPrePurchaseRequestDetail.pass(ids, this.auditForm.supplierName, this.auditForm.purchaseAttribute).then(res => {
        this.auditDialog = false
        this.crud.toQuery()
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    // 推送
    doAudit(datas) {
      this.auditDialog = true
      // this.auditForm.num = datas.length
      // let ids = datas.map(item => item.id);
      // let params = {
      //   'prePurchaseRequestId': []
      // }
      // params.prePurchaseRequestId = ids
      // console.log(ids)
      // crudPrePurchaseRequestDetail.query(params).then(res => {
      //   this.auditForm.index = res.totalElements
      // }).catch(err => {
      //   console.log(err.response.data.message)
      // })
      //dictDetail.get

    },
    getStatusLable(row, column, cellValue, index) {
      const key = row[column.property]
      // console.log(this.dict.label.aduit_status[key])
      return this.dict.label.aduit_status[key]
        // if (key === 0) {
        //   return '未审核'
        // } else if (key === 1) {
        //   return '已审核'
        // } else {
        //   return '已取消'
        // }
    },
    // 上传文件
    upload() {
      this.$refs.upload.submit()
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.name = file.name
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.uploadDialog = false
      this.crud.status.add = CRUD.STATUS.NORMAL
      this.crud.resetForm()
      this.crud.toQuery()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 5000
      })
      this.loading = false
    }
  },
  created() {
    this.crud.optShow = {
      add: true,
      edit: false,
      del: true,
      download: false,
      reset: false
    },
    supplierRequest.listAll().then(res => {
      this.suppliers = res.content
    }),
    this.query.createBy = this.user.username,
    this.query.status = 0,
    this.crud.toQuery()
    defaultForm.expectedDeliveryDate = this.calculateDate(7)
    this.crud.page.size = 500
  }
}
</script>

<style scoped>

</style>
